package com.xzakota.minesweeper.ui.frame;

import com.xzakota.minesweeper.R;
import com.xzakota.minesweeper.controller.Game;
import com.xzakota.minesweeper.controller.GameResource;
import com.xzakota.minesweeper.ui.IWindow;
import com.xzakota.minesweeper.ui.dialog.templae.OptionDialog;
import com.xzakota.minesweeper.widget.CellLabel;
import com.xzakota.minesweeper.widget.GameCellMapPanel;
import com.xzakota.minesweeper.widget.GameInfoPanel;
import com.xzakota.minesweeper.widget.menu.SinglePlayerGameMenuBar;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * 单人游戏界面
 *
 * @author Xzakota
 */
public class SinglePlayerGameFrame extends AbstractBaseFrame {
    private final Game game;

    public SinglePlayerGameFrame(IWindow parent) {
        super("单人游戏");

        game = new Game(this);

        setIconImage(GameResource.getImageResource(R.Image.APP_ICON));
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        CellLabel.loadResource();
        GameInfoPanel.loadResource();

        initLayout();

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                OptionDialog optionDialog = new OptionDialog("是否退出游戏？记录无法保存哦！");
                optionDialog.setConfirmAction(evt -> {
                    optionDialog.closeWindow();
                    Game.dispatchEvent("exitGame");
                });
                optionDialog.showWindow();
            }

            @Override
            public void windowClosed(WindowEvent e) {
                if (parent != null) {
                    parent.showWindow();
                }
            }
        });
    }

    public void initLayout() {
        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.setBackground(new Color(0xC0CCDA));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));

        setJMenuBar(new SinglePlayerGameMenuBar(game.model));

        GameInfoPanel controlPanel = new GameInfoPanel(game.model);
        contentPanel.add(controlPanel, BorderLayout.SOUTH);

        GameCellMapPanel minePanel = new GameCellMapPanel(game.model);
        contentPanel.add(minePanel);

        setContentPane(contentPanel);
    }

    @Override
    public void showWindow() {
        game.levelChangeListener = this::updateUI;
        game.newGame();
        updateUI();

        super.showWindow();
    }
}
